using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace TermitesMagnets
{
    public class Termite : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private GameplayScreen GameScreen;
        private static int width;
        private static int height;
        private bool isCounted;
        private static Texture2D texture;
        private Color color;
        private int colorIndex;
        private Vector2 position;
        private BoundingBox boundingBox;
        private Level parent;
        private Vector2 speed;
        private TargetRect currentRect;

        public Color Color{ get { return color; } set { color = value; }}
        public int ColorIndex{ get { return colorIndex; } set { colorIndex = value; }}
        public Vector2 Position{ get { return position; } set { position = value; }}
        public BoundingBox BoundingBox{ get { return boundingBox; } set { boundingBox = value; }}
        public Level Parent{ get { return parent; }}
        public Vector2 Speed{ get { return speed; } set { speed = value; }}
        public bool IsCounted{ get { return isCounted; } set { isCounted = value; }}
        public static Texture2D Texture{ get { return Termite.texture; }}

        public Termite(Game game,Level parent, Vector2 position, Color color, int colorIndex)
            : base(game)
        {
            this.parent = parent;
            this.GameScreen = GameplayScreen.GlobalGame;
            this.ColorIndex = colorIndex;
            this.Color = color;
            this.speed = new Vector2(0, 0);
            this.position = position;
            this.parent.AddComponent(this);
            this.currentRect = null;
        }

        public static void LoadContent(ContentManager Content)
        {
            Termite.texture = Content.Load<Texture2D>(@"Images\termite4");
            Termite.height = texture.Height;
            Termite.width = texture.Width;
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here

            base.Initialize();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            if (GameScreen.IsActive)
            {
                Termite termite = this;
                Level currentLevel = parent;
                Random Rand = Game1.Rand;
                Matrix rotationMatrixOdd = Matrix.CreateRotationZ((float)(Rand.Next(-20, 20)) / 10);
                termite.IsCounted = false;
                float timeDiff = (float)gameTime.ElapsedGameTime.TotalSeconds;

                foreach (Magnet magnet in currentLevel.Magnets)
                {

                    magnet.Interact(termite, timeDiff);
                }

                Vector2 newPos;
                if (Rand.Next() % 2 == 0)
                {
                    newPos = termite.Position + Vector2.Transform(termite.Speed, rotationMatrixOdd) * timeDiff;
                }
                else
                {
                    newPos = termite.Position + termite.Speed * timeDiff;
                }

                /* Lame try
                if (!currentLevel.Board.IsInWorld(newPos))
                {
                    // Try to put back in the world
                    termite.Speed = Vector2.Transform(termite.Speed, rotationMatrixFlip) * 100;
                    newPos = currentLevel.Board.BringToWorld(newPos);
                    newPos = termite.Position + termite.Speed * timeDiff*100;
                }
                */
                // Try to move termite to new location (if the new location is free)
                if (((int)newPos.X == (int)termite.Position.X) && ((int)newPos.Y == (int)termite.Position.Y) ||
                    (currentLevel.Board.isFree((int)newPos.X, (int)newPos.Y)))
                {
                    // Free old location
                    currentLevel.Board.Clear((int)termite.Position.X, (int)termite.Position.Y);
                    termite.Position = newPos;
                    // Occupy new position
                    currentLevel.Board.Occupy((int)newPos.X, (int)newPos.Y);
                }
                else
                {
                    // If the new location is already taken by another termite -> stop
                    termite.Speed = new Vector2(0, 0);
                }
            }
            base.Update(gameTime);
        }

        public Rectangle GetRect()
        {
            return new Rectangle((int)position.X, (int)position.Y, Termite.width, Termite.height);
        }

        public override void Draw(GameTime gameTime)
        {
            GameScreen.SpriteBatch.Begin();
            Color currentColor;
            if (isCounted)
                currentColor = Color.White;
            else
                currentColor = color;
            GameScreen.SpriteBatch.Draw(texture, GameScreen.CurrentLevel.Board.WorldPositionToReal(position), currentColor);
            GameScreen.SpriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
